package com.framework.workflow.cmd;

import com.framework.common.util.SpringUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.Process;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.impl.history.HistoryManager;
import org.flowable.engine.impl.persistence.entity.ActivityInstanceEntity;
import org.flowable.engine.impl.persistence.entity.ActivityInstanceEntityManager;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityManager;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.ProcessDefinitionUtil;
import org.flowable.task.api.Task;
import org.flowable.task.service.TaskService;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;

import java.util.Date;
import java.util.List;

public class JumpAnyWhereCmd implements Command<Void> {
    private final RepositoryService repositoryService = SpringUtils.getBean(RepositoryService.class);

    private final List<Task> tasks;

    private final String targetNodeId;

    /**
     * @param tasks 当前任务ID
     * @param targetNodeId 目标节点定义ID
     */
    public JumpAnyWhereCmd(List<Task> tasks, String targetNodeId) {
        this.tasks = tasks;
        this.targetNodeId = targetNodeId;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        // 获取任务实例管理类
        TaskService taskService =  CommandContextUtil.getTaskService(commandContext);

        // 获取 ExecutionEntityManager（用于管理执行实例）
        ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);

        // 获取当前任务实例
        TaskEntity currentTask = (TaskEntity) tasks.get(0);

        // 获取 HistoryManager（记录历史数据）
        HistoryManager historyManager = CommandContextUtil.getHistoryManager(commandContext);

        // 通过executionId获取执行实例（Flowable新方式）
        ExecutionEntity execution = executionEntityManager.findById(currentTask.getExecutionId());

        // 获取流程定义和BPMN模型
        String processDefinitionId = execution.getProcessDefinitionId();
        BpmnModel bpmnModel = ProcessDefinitionUtil.getBpmnModel(processDefinitionId);
        Process process = bpmnModel.getMainProcess();
        FlowElement flowElement = process.getFlowElement(this.targetNodeId);

        ActivityInstanceEntityManager activityInstanceEntityManager = CommandContextUtil.getActivityInstanceEntityManager(commandContext);
        // 会签要删除多个
        tasks.forEach(task -> {
            // 获取任务对应的执行实例
            ExecutionEntity taskExecution = executionEntityManager.findById(((TaskEntity)task).getExecutionId());
            // 获取当前活动的ActivityInstance
            ActivityInstanceEntity activityInstance = activityInstanceEntityManager
                    .findUnfinishedActivityInstance(taskExecution);

            // 记录历史
            if (activityInstance != null) {
                historyManager.recordActivityEnd(activityInstance);
            }

            // 通知任务节点结束(更新act_hi_taskinst)
            historyManager.recordTaskEnd((TaskEntity)task, taskExecution, null, new Date(System.currentTimeMillis()));
            // 删除正在执行的当前任务
            taskService.deleteTask((TaskEntity) task, true);
        });

        // 此时设置执行实例的当前活动节点为目标节点
        execution.setCurrentFlowElement(flowElement);

        // 向operations中压入继续流程的操作类
        CommandContextUtil.getAgenda().planContinueProcessOperation(execution);

        return null;
    }
}

